package com.beiding.hotcode;

import java.io.*;

class FileUtils {

    final static File classpathRoot;
    final static String classpathRootString;

    //无法找到的jar包文件的托管
    private static final File cannotFindJarPath;

    static {
        try {

            String folder = System.getProperty("java.io.tmpdir");

            File root = new File(folder, "hotcode");
            root.mkdirs();

            cannotFindJarPath = new File(root, "libs");
            if (!cannotFindJarPath.exists()) {
                cannotFindJarPath.mkdirs();
            }
            classpathRoot = new File(root, "classpath");
            if (!classpathRoot.exists()) {
                classpathRoot.mkdirs();
            }
            classpathRootString = classpathRoot.getAbsolutePath();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    static File copyJarFile(InputStream inputStream, String name) {
        File file = new File(cannotFindJarPath, name);
        if (file.exists()) {
            return file;
        }
        try {
            file.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            copy(inputStream, fileOutputStream);
            fileOutputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return file;
    }

    static File createClassFile(String classname) {
        return new File(classpathRoot, classname.replace(".", File.separator) + ".class");
    }

    static void copy(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buff = new byte[1024 * 4];
        int len;
        while ((len = inputStream.read(buff)) != -1) {
            outputStream.write(buff, 0, len);
        }
    }

    static byte[] readFileData(File file) throws IOException {
        try (InputStream is = new FileInputStream(file)) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            copy(is, baos);
            return baos.toByteArray();
        }
    }

}
